<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/4/19
* Time: 8:41
*/
namespace app\admin\controller;

use app\admin\controller\Department;
use app\admin\model\DepartmentModel;
use app\admin\model\MemberModel;
use app\admin\model\RoleModel;
use think\Db;
use app\admin\model\OrderModel;

class Member extends Base
{
	/**
	* 会员管理
	* 黄
	* 18-4-19
	*/
	public function index ()
	{
		return $this->fetch();
	}
	/**
	* 会员列表
	* $param               搜索参数
	* director             主任权限
	* executive_director   主管权限
	* memberList           咨询师权限
	*/
	public function memberList ()
	{
		if (request()->isAjax()) {
			$uid = session('id');
			$param = input('param.');
			$limit = $param['pageSize'];
			$offset = ($param['pageNumber'] - 1) * $limit;
			$where = [];
			if (!empty($param['name'])) {
				$where['name'] = ['like', '%' . $param['name'] . '%'];
			}
			if (!empty($param['phone'])) {
				$where['phone'] = ['like', '%' . $param['phone'] . '%'];
			}
			if (!empty($param['grade'])) {
				$where['grade'] = $param['grade'];
			}
			if (!empty($param['status'])) {
				$where['status'] = (int)$param['status'];
			}
			$where['delete_status'] = array('neq',2);

			$member = new MemberModel();
			// 搜人
			$staff = input('param.staff');
			$ids = DB::name('user')->where('real_name','like', '%'.$staff.'%')->column('id');

			$idArr =[];
			if(!empty(session('can_see')[0])){
				foreach (session('can_see') as $v){
					foreach($ids as $va){
						if($v['create_uid'] == $va){
							array_push($idArr,$v['create_uid']);
						}
					}
				}
			}
			if($staff && empty($idArr)){
				$idArr =[-1];
			}
			// 搜部门
			$departId = input('param.depart_id');
			$departModel = new DepartmentModel();
			$roleModel = new RoleModel();
			$departIds = $departModel->getSonsByPid($departId);
			array_push($departIds,['id'=>$departId]);
			$roles = [];
			foreach ($departIds as $k => $v){
				if(DB::name('role')->where('department_id',$v['id'])->find()) {
					$roles[$k] = $roleModel->getUsersByDepartId($v['id']);
				}
			}
			$users = [];
			foreach ($roles as $k => $v){
				foreach($v as $ke => $va){
					array_push($users,$va);
				}
			}
			$users = array_merge(array_filter($users));

			$member->where(function($query)use($idArr){
				foreach($idArr as $v){
					$query->whereOr('create_uid',$v);
				}
			});
			$member->where(function($query)use($users){
				foreach($users as $v){
					$query->whereOr('create_uid',$v);
				}
			});

			$selectResult = $member->getMemberByWhere($where, $offset, $limit);
			$i = 0;
			foreach($selectResult as $key=>&$vo){
				$vo['statusN'] = Db::name('member_attr')->where(['id'=>$vo['status']])->value('name');
				//强制释放
				if ($vo['status'] != 8){
					if($vo['relation_id'] == $uid){
						$vo['operate'] = showOperate($this->makeButton1($vo['id']));
					}else{
						$vo['operate'] = showOperate($this->makeButton4($vo['id']));//强制释放
					}
				}else{
					$vo['operate'] = showOperate($this->makeButton2($vo['id']));
				}
				$vo['gradeN'] = Db::name('member_attr')->where(['id'=>$vo['grade']])->value('name');
				//时间
				if(!empty($param['time'])){
					$start_time = strtotime(explode(" - ",$param['time'])[0]." 00:00:00");
					$end_time = strtotime(explode(" - ",$param['time'])[1]." 23:59:59");
					if($vo['time'] < $start_time || $vo['time'] > $end_time){
						unset($selectResult[$key]);
						$i ++ ;
					}
				}
			}
			$return['rows'] = $selectResult;
			$member = new MemberModel();
			$member->where(function($query)use($idArr){
				foreach($idArr as $v){
					$query->whereOr('create_uid',$v);
				}
			});
			$member->where(function($query)use($users){
				foreach($users as $v){
					$query->whereOr('create_uid',$v);
				}
			});
			$return['total'] = $member->getAllMember($where) - $i;  // 总数据
			return json($return);
		}
		//客户等级
		$gradeArr = Db::name('member_attr')->where(['pid'=>1])->select();
		//客户状态
		$statusArr = Db::name('member_attr')->where(['pid'=>5])->select();
		$this->assign([
			'gradeArr' => $gradeArr,
			'statusArr' => $statusArr
		]);
		return $this->fetch();
	}
	/**
	* 强制释放
	* status 改变
	*/
	public function releaseMem(){
		if(request()->isAjax()){
			$param = $_POST['param'];
			$member = new MemberModel();
			$returnMsg = $member->release($param);
			return $returnMsg;
		}
	}
	/**
	* 伪删除会员
	*/
	public function deleteList ()
	{
		$param = $_POST['param'];
		$member = new MemberModel();
		$returnMsg = $member->delMember($param);
		return $returnMsg;
	}
	//查看会员信息
	public function checkMember ()
	{
		$id = (int)input('param.id');
		$member = new MemberModel();
		$returnMsg = $member->getOneMember($id);
		$returnMsg['statusN'] = Db::name('member_attr')->where(['id'=>$returnMsg['status']])->value('name');
		$returnMsg['gradeN'] = Db::name('member_attr')->where(['id'=>$returnMsg['grade']])->value('name');
		$returnMsg['entry_time'] = date('Y-m-d',$returnMsg['entry_time']);
		//客户等级
		$gradeArr = Db::name('member_attr')->where(['pid'=>1])->select();
		foreach ($gradeArr as $key => $value){
			if ($value['id'] == $returnMsg['grade']){
				unset($gradeArr[$key]);
			}
		}
		//客户状态
		$statusArr = Db::name('member_attr')->where(['pid'=>5])->select();
		foreach ($statusArr as $k => $val){
			if ($val['id'] == $returnMsg['status']){
				unset($statusArr[$k]);
			}
		}
		$this->assign([
			'memberArr' => $returnMsg,
			'gradeArr' => $gradeArr,
			'statusArr' => $statusArr
		]);
		return $this->fetch();
	}

	/**
	* 修改客户信息
	*/
	public function memberEdit ()
	{
		$member = new MemberModel();
		if (request()->isPost()){
			$param = input('post.');
			$flag = $member->memberEdit($param);
			return json(msg($flag['code'], $flag['data'], $flag['msg']));
		}
		$id = input('param.id');
		$returnMsg = $member->getOneMember($id);
		$returnMsg['statusN'] = Db::name('member_attr')->where(['id'=>$returnMsg['status']])->value('name');
		$returnMsg['gradeN'] = Db::name('member_attr')->where(['id'=>$returnMsg['grade']])->value('name');
		$returnMsg['time'] = date('Y-m-d',$returnMsg['time']);
		//客户等级
		$gradeArr = Db::name('member_attr')->where(['pid'=>1])->select();
		foreach ($gradeArr as $key => $value){
			if ($value['id'] == $returnMsg['grade']){
				unset($gradeArr[$key]);
			}
		}
		//客户状态
		$statusArr = Db::name('member_attr')->where(['pid'=>5])->select();
		foreach ($statusArr as $k => $val){
			if ($val['id'] == $returnMsg['status']){
				unset($statusArr[$k]);
			}
		}
		//支付方式
		$payTypeArr = Db::name('member_attr')->where(['pid'=>10])->select();

		$this->assign([
			'mid'        => $id,
			'memberArr'  => $returnMsg,
			'gradeArr'  => $gradeArr,
			'statusArr' => $statusArr,
			'payTypeArr' => $payTypeArr,
		]);
		return $this->fetch();
	}
	/**
	* 根据时间段搜索相对应的追踪信息
	* @param $KL-time
	*/
	public function trackList(){
		if (request()->isAjax()){
			$param = input('post.');
			if (empty($param['time'])){
				return msg(-1, '','时间不能为空');
			}
			$where = [];
			$where['m_id'] = $param['mid'];
			//时间
			$start_time = strtotime(explode(" - ",$param['time'])[0].'00:00:00');
			$end_time = strtotime(explode(" - ",$param['time'])[1].'24:59:59');
			$where['time'] = array('between',[$start_time,$end_time]);
			$member = new MemberModel();
			$result = $member->getTrackList($where);
			return json($result);
		}
	}
	/**
	* 添加跟踪信息
	* @param $_post
	* @return array
	*/
	public function addTrack ()
	{
		$member = new MemberModel();
		$mid = (int)input('param.mid');
		$Mname = Db::name('member')->where(['id'=>$mid])->value('name');
		$uid = $_SESSION['think']['id'];
		$Uname = Db::name('user')->where(['id'=>$uid])->value('real_name');

		if (request()->isPost()){
			$param = input('post.');
			$param['u_id'] = $uid;
			$param['time'] = strtotime($_POST['years'].$_POST['times']);
			$flag = $member->addTrack($param);
			return json(msg($flag['code'], $flag['data'], $flag['msg']));
		}

		$this->assign([
			'mid'   => $mid,
			'Mname' => $Mname,
			'Uname' => $Uname
		]);
		return $this->fetch();
	}
	/**
	* 查看跟踪信息
	* @param $id
	* @return array
	*/
	public function trackMember ()
	{
		$member = new MemberModel();
		if(request()->isAjax()){
			$id = $_POST['tid'];
			$track = $member->getTrackMember($id);
			$track['typeN'] = Db::name('member_attr')->where(['id'=>$track['type']])->value('name');
			return json($track);
		}
	}
	/**
	* 删除跟踪信息
	* @param $id
	* @return array
	*/
	public function trackDel ()
	{
		$id = $_POST['tid'];
		$member = new MemberModel();
		$returnMsg = $member->delTrack($id);
		return $returnMsg;
	}
	/**
	* 公共客户列表
	* 主管及主任以上可看
	* 属于资源库客户
	* @param $id
	* @return array
	*/
	public function wholeList ()
	{
		if (request()->isAjax()) {
			$param = input('param.');
			$limit = $param['pageSize'];
			$offset = ($param['pageNumber'] - 1) * $limit;
			$where = [];
			if (!empty($param['name'])) {
				$where['name'] = ['like', '%' . $param['name'] . '%'];
			}
			if (!empty($param['phone'])) {
				$where['phone'] = ['like', '%' . $param['phone'] . '%'];
			}
			$where['status'] = ['eq',9];//强制使用分配客源
			$where['first_relation'] = ['eq',0];//由资源库录入的客户没有第一关联人
			$member = new MemberModel();
			$selectResult = $member->getMemberByWhere($where, $offset, $limit);
			foreach($selectResult as $key=>&$vo){
				$vo['operate'] = showOperate($this->makeButton3($vo['id']));
				$vo['status'] = Db::name('member_attr')->where(['id'=>$vo['status']])->value('name');
			}
			$return['total'] = $member->getAllMember($where);  // 总数据
			$return['rows'] = $selectResult;
			return json($return);
		}
		return $this->fetch();
	}
	/**
	* 添加资料库客源
	*/
	public function addResMember(){
		if(request()->isPost()){
			$param = input('post.');
			$param['grade'] = 0;
			$param['status'] = 9;
			$param['source'] = 1;
			$MemberModel = new MemberModel();
			$flag = $MemberModel->addResMember($param);
			return json(msg($flag['code'], $flag['data'], $flag['msg']));
		}
		return $this->fetch();
	}
	/**
	* 文件导入资源客户库数据
	*/
	public function resMemExcel(){
		$id = input('post.id');
		$path = DB::name('attachment')->where('id',$id)->value('path');
		vendor("PHPExcel.Classes.PHPExcel");
		$PHPExcel = new \PHPExcel();
		$objRead = new \PHPExcel_Reader_Excel2007();   //建立reader对象
		if(!$objRead->canRead($path)){
			$objRead = new \PHPExcel_Reader_Excel5();
			if(!$objRead->canRead($path)){
				die('No Excel!');
			}
		}
		$cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

		$obj = $objRead->load($path);  //建立excel对象
		$currSheet = $obj->getSheet(0);   //获取指定的sheet表
		$columnH = $currSheet->getHighestColumn();   //取得最大的列号
		$columnCnt = array_search($columnH, $cellName);
		$rowCnt = $currSheet->getHighestRow();   //获取总行数

		$data = array();
		for($_row=1; $_row<=$rowCnt; $_row++){  //读取内容
			for($_column=0; $_column<=$columnCnt; $_column++){
				$cellId = $cellName[$_column].$_row;
				$cellValue = $currSheet->getCell($cellId)->getValue();
				if($cellValue instanceof PHPExcel_RichText){   //富文本转换字符串
					$cellValue = $cellValue->__toString();
				}
				$data[$_row][$cellName[$_column]] = $cellValue;
			}
		}
		$inData = [];
		foreach($data as $k => $v){
			if($k>1){
				if($v['A'] == ""){
					unset($data[$k]);
				}else{
					$inData[$k] = [
						'name' => $v['A'],
						'phone' => $v['B'],
						'weixin' => $v['E'],
						'qq' => $v['F'],
						'adress' => $v['H'],
						'grade'  => 0,
						'status' => 9,
						'source' => 1,
					];
				}
			}else{
				unset($data[$k]);
			}
		}

		DB::startTrans();
		try{
			DB::commit();
			foreach($inData as $v){
				DB::name('member')->insert($v);
			}
			return ['code'=>1,'msg'=>'导入成功'];
		}catch(\Exception $e){
			DB::rollback();
			return ['code'=>0,'msg'=>'导入失败:'.$e->getMessage()];
		}
	}
	/**
	* 分配客户会员(主管OR主任)
	* 添加
	*/
	public function insertMember ()
	{
		$param = input('post.');
		$paramArr = $param['param'];
		$member = new MemberModel();
		$where = [];
		//        $where['status'] = 9;
		$where['first_relation'] = $param['uid'];
		$where['entry_time'] = time();
		$where['source'] = 1;//客户来源
		$where['create_uid'] = $param['uid'];//创建者id

		$returnMsg = $member->insMember($paramArr,$where);
		return $returnMsg;
	}
	/**
	* 客户属性
	* grade (等级) status(客户状态)
	* 确定 值 status 1.释放 2.成交 (不可更改)
	*/
	public function memberAttr (){
		if(request()->isAjax()){
			$depart = new DepartmentModel();
			$departs = $depart->getDepartmentList();
			$departs = getTree(objToArray($departs), false);
			return json(msg(1, $departs, 'ok'));
		}
		return $this->fetch();
	}
	/**
	* 分享列表(增)
	* 由分享的客户组成的列表
	* 可由主管分配
	*/
	public function shareList(){
		$uid = session('id');
		$role_id = Db::name('user')->where(['id'=>$uid])->value('role_id');
		$department_id =Db::name('role')->where(['id'=>$role_id])->value('department_id');
		$RoleModel = new RoleModel();
		$users = $RoleModel->getUsersByDepartId($department_id);//获取当前登录人所在部门的所有职员
		$userK = [];
		foreach($users as $key => $val){
			$userK[$key]['id'] = $val;
			$userN = Db::name('user')->where(['id'=>$val])->value('real_name');
			$userK[$key]['name'] = $userN;
		}
		$king['id'] = array('in',$users);
		$usersArr = Db::name('user')->where($king)->value('real_name');

		if (request()->isAjax()) {
			$param = input('param.');
			$limit = $param['pageSize'];
			$offset = ($param['pageNumber'] - 1) * $limit;
			$where = [];
			if (!empty($param['name'])) {
				$where['name'] = ['like', '%' . $param['name'] . '%'];
			}
			if (!empty($param['phone'])) {
				$where['phone'] = ['like', '%' . $param['phone'] . '%'];
			}
			if (!empty($param['grade'])) {
				$where['grade'] = $param['grade'];
			}
			$where['share'] = 1;//分享状态
			$where['create_uid'] = array('in',$users);
			$member = new MemberModel();
			$selectResult = $member->getMemberByWhere($where, $offset, $limit);
			foreach($selectResult as $key=>&$vo){
				$vo['status'] = Db::name('member_attr')->where(['id'=>$vo['status']])->value('name');
				$vo['grade'] = Db::name('member_attr')->where(['id'=>$vo['grade']])->value('name');
				$vo['operate'] = showOperate($this->makeButton3($vo['id']));
			}
			$return['total'] = $member->getAllMember($where);  // 总数据
			$return['rows'] = $selectResult;

			return json($return);
		}
		//客户等级
		$gradeArr = Db::name('member_attr')->where(['pid'=>1])->select();
		$this->assign([
			'gradeArr' => $gradeArr,
			'userK' => $userK
		]);
		return $this->fetch();
	}
	/**
	* 分享/跟踪的职员分配
	*/
	public function ajaxShare(){
		if (request()->isAjax()) {
			$param = input('post.');
			if(empty($param['uid'])){
				return json(['code'=>2,'msg'=>'请选择分配职员']);
			}
			if(isset($param['status'])){
				$data['status'] = 6;
			}else{
				$data['share'] = 0;
			}
			$data['create_uid'] = $param['uid'];
			$data['second_relation'] = $param['uid'];
			$data['second_time'] = time();
			$memberModel = new MemberModel();
			$king = $memberModel->ajaxShare($param,$data);
			return json($king);
		}
	}
	/**
	* 释放列表(增)
	* 释放出来的列表
	* 由主管分配
	*/
	public function releaseList(){
		$uid = session('id');
		$role_id = Db::name('user')->where(['id'=>$uid])->value('role_id');
		$department_id =Db::name('role')->where(['id'=>$role_id])->value('department_id');
		$RoleModel = new RoleModel();
		$users = $RoleModel->getUsersByDepartId($department_id);//获取当前登录人所在部门的所有职员
		$userK = [];
		foreach($users as $key => $val){
			$userK[$key]['id'] = $val;
			$userN = Db::name('user')->where(['id'=>$val])->value('real_name');
			$userK[$key]['name'] = $userN;
		}
		$king['id'] = array('in',$users);
		$usersArr = Db::name('user')->where($king)->value('real_name');

		if (request()->isAjax()) {
			$param = input('param.');
			$limit = $param['pageSize'];
			$offset = ($param['pageNumber'] - 1) * $limit;
			$where = [];
			if (!empty($param['name'])) {
				$where['name'] = ['like', '%' . $param['name'] . '%'];
			}
			if (!empty($param['phone'])) {
				$where['phone'] = ['like', '%' . $param['phone'] . '%'];
			}
			if (!empty($param['grade'])) {
				$where['grade'] = $param['grade'];
			}
			$where['share'] = 0;//分享状态
			$where['status'] = 8;//客户状态
			$where['create_uid'] = array('in',$users);
			$member = new MemberModel();
			$selectResult = $member->getMemberByWhere($where, $offset, $limit);
			foreach($selectResult as $key=>&$vo){
				$vo['status'] = Db::name('member_attr')->where(['id'=>$vo['status']])->value('name');
				$vo['grade'] = Db::name('member_attr')->where(['id'=>$vo['grade']])->value('name');
				$vo['operate'] = showOperate($this->makeButton3($vo['id']));
			}
			$return['total'] = $member->getAllMember($where);  // 总数据
			$return['rows'] = $selectResult;

			return json($return);
		}
		//客户等级
		$gradeArr = Db::name('member_attr')->where(['pid'=>1])->select();
		$this->assign([
			'gradeArr' => $gradeArr,
			'userK' => $userK
		]);
		return $this->fetch();
	}
	/**
	* 拼装操作按钮
	* @param $id 跟踪记录
	* @return array
	*/
	private function makeButton1($id)
	{
		return [
			'跟踪记录' => [
				'auth' => 'member/memberedit',
				'href' => url('member/memberedit', ['id' => $id]),
				'btnStyle' => 'success',
				'icon' => 'fa fa-paste',
			]
		];
	}
	/**
	* 查看信息 $id
	*/
	private function makeButton2($id)
	{
		return [
			'查看信息' => [
				'auth' => 'member/checkmember',
				'href' => url('member/checkmember', ['id' => $id]),
				'btnStyle' => 'danger',
				'icon' => 'fa fa-search',
			]
		];
	}
	/**
	* 添加按钮 $id
	* 公共客源库分配客源
	* distribution
	*/
	private function makeButton3($id)
	{
		return [
			'分配客源' => [
				'auth' => 'member/insertmember',
				'href' => 'javascript:distribution('.$id.')',
				'btnStyle' => 'danger',
				'icon' => 'fa fa-search',
			]
		];
	}
	/**
	* 添加按钮 $id
	* 强制释放
	* distribution
	*/
	private function makeButton4($id)
	{
		return [
			'查看信息' => [
				'auth' => 'member/checkmember',
				'href' => url('member/checkmember', ['id' => $id]),
				'btnStyle' => 'danger',
				'icon' => 'fa fa-search',
			],
			'强制释放' => [
				'auth' => 'member/insertmember',
				'href' => 'javascript:releasemem('.$id.')',
				'btnStyle' => 'danger',
				'icon' => 'fa fa-search',
			]
		];
	}
}
